package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;
    //会员数量折线图数据
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
        //使用模拟数据测试对象格式是否能够转为echarts所需的数据格式
        Map<String,Object> map=new HashMap<>();
        List<String> months=new ArrayList<>();

        Calendar calendar=Calendar.getInstance();  //获得日历对象
        //计算过去一年的时间
        calendar.add(Calendar.MONTH,-12);  //获得当前时间往前推12个月的时间
        for(int i=0;i<12;i++){
            calendar.add(Calendar.MONTH,1);  //获得当前时间往后推一个月的日期
            Date date = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy.MM").format(date));
        }

        map.put("months",months);

        List<Integer> memberAmount =memberService.findMemberAmountByMouths(months);
        map.put("memberAmount",memberAmount);

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }


    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        /*Map<String,Object> data=new HashMap<>();
        List<String> setmealNames=new ArrayList<>();
        setmealNames.add("直接访问");
        setmealNames.add("邮件营销");
        setmealNames.add("联盟广告");
        data.put("setmealNames",setmealNames);
        List<Map<String,Object>> setmealCount=new ArrayList<>();
        Map map1=new HashMap();
        map1.put("name","直接访问");
        map1.put("value",335);
        setmealCount.add(map1);
        Map map2=new HashMap();
        map2.put("name","邮件营销");
        map2.put("value",310);
        setmealCount.add(map2);
        Map map3=new HashMap();
        map3.put("name","联盟广告");
        map3.put("value",358);
        setmealCount.add(map3);
        data.put("setmealCount",setmealCount);
        return new Result(true,"套餐占比数据查询成功",data);*/

        try {
            Map<String, Object> data = new HashMap<>();

            List<Map<String, Object>> setmealCount = setmealService.findSetmealCount();

            data.put("setmealCount", setmealCount);

            List<String> setmealNames = new ArrayList<>();

            for (Map<String, Object> map : setmealCount) {
                String name = (String) map.get("name");   //套餐名称
                setmealNames.add(name);
            }

            data.put("setmealNames", setmealNames);

            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, data);
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    @RequestMapping("/getSetmealSex")
    public Result getSetmealSex(){
        Map<String, Object> data = new HashMap<>();
        try {
            List<Map<String,Object>> sexCount = memberService.findMemberSexCount();

            List<Map<String,Object>> list = new ArrayList<>();
            List<String> sexNames = new ArrayList<>();
            for (Map<String, Object> map : sexCount) {
                String name = (String) map.get("name");//性别名称
                if (name == null){
                    name = "未知性别";
                    map.put("name",name);
                }else if (name.equals("1")){
                    name = "男";
                    map.put("name",name);
                }else if (name.equals("2")){
                    name = "女";
                    map.put("name",name);
                }
                sexNames.add(name);
                list.add(map);
            }
            data.put("sexCount",list);
            data.put("sexNames",sexNames);
            return new Result(true,"获取会员性别数据成功",data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"获取会员性别数据失败");
        }
    }

@Reference
private ReportService reportService;

    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        try {
            Map<String, Object> data = reportService.getBusinessReportData();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,data);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }


    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try{
            Map<String,Object> result = reportService.getBusinessReportData();
            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            String filePath = request.getSession().getServletContext().getRealPath("template")+ File.separator+"report_template.xlsx";
            //基于提供的Excel模板文件在内存中创建一个Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //读取第一个工作表
            XSSFSheet sheet = excel.getSheetAt(0);

            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;
            for(Map map : hotSetmeal){//热门套餐
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheet.getRow(rowNum ++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }

            //使用输出流进行表格下载,基于浏览器作为客户端下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//指定以附件形式进行下载
            excel.write(out);

            out.flush();
            out.close();
            excel.close();
            return null;
        }catch (Exception e){
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }












    //会员数量折线图数据
    @RequestMapping("/getMemberReport111")
    public Result getMemberReport111(String startTime,String endTime){
        System.out.println(startTime);  //2019/3/15
        System.out.println(endTime);    //2019/5/23
        String startTimeYear = startTime.split("/")[0];
        String startTimeMonth = startTime.split("/")[1];
        String startTimeDay = startTime.split("/")[2];
        String endTimeYear = endTime.split("/")[0];
        String endTimeMonth = endTime.split("/")[1];
        String endTimeDay = endTime.split("/")[2];

        Map<String,Object> map=new HashMap<>();
        //如果同年同月
        if(startTimeYear.equals(endTimeYear)&&startTimeMonth.equals(endTimeMonth)){
            System.out.println("----------------------------111111111111111");
            List<String> months=new ArrayList<>();
            months.add(startTimeYear+"/"+startTimeMonth);
            map.put("months",months);
            List<Integer> list=new ArrayList<>();
            Integer count=memberService.findMemberCountBySameYearAndMonth(startTime,endTime);
            list.add(count);
            map.put("memberAmount",list);
            System.out.println(map);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
        }
        //如果同年不同月
        if(startTimeYear.equals(endTimeYear)){
            System.out.println("----------------------------22222222222222222");
            List<String> months=new ArrayList<>();
            for(int i=Integer.parseInt(startTimeMonth);i<=Integer.parseInt(endTimeMonth);i++){
                months.add(startTimeYear+"/"+i);
            }
            //第一月就是五月  比如2019-05-12  到  2019-08-22
            String end=startTimeYear+"/"+startTimeMonth+"/"+31;
            List<Integer> countList=new ArrayList<>();
            Integer firstMonthCount=memberService.findMemberCountBySameYearAndMonth(startTime,end);
            countList.add(firstMonthCount);
            System.out.println(firstMonthCount);
            String s="";
            String e="";
            if(Integer.parseInt(endTimeMonth)-Integer.parseInt(startTimeMonth)>1){  //其中夹着月份(不是连续的月份)
                for(int i=Integer.parseInt(startTimeMonth)+1;i<Integer.parseInt(endTimeMonth);i++){
                    s=startTimeYear+"/"+i+"/"+1;
                    e=endTimeYear+"/"+i+"/"+31;
                    System.out.println(s);
                    System.out.println(e);
                     Integer betweenCount=memberService.findMemberCountBySameYearAndMonth(s,e);
                     countList.add(betweenCount);
                }
            }
            //最后一月
            String end1=endTimeYear+"/"+endTimeMonth+"/"+1;
            System.out.println(end1);
            Integer count222 = memberService.findMemberCountBySameYearAndMonth(end1, endTime);
            System.out.println(count222);
            countList.add(count222);
            map.put("months",months);
            map.put("memberAmount",countList);

            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
        }
        //不同年
        if(!startTimeYear.equals(endTimeYear)){
            //第一个月

            List<String> months=new ArrayList<>();
            List<Integer> list=new ArrayList<>();
            months.add(startTimeYear+"/"+startTimeMonth);
            Integer b=memberService.findMemberCountBySameYearAndMonth(startTime,startTimeYear+"/"+startTimeMonth+"/"+31);
            list.add(b);

            //year =2018
            int year=Integer.parseInt(startTimeYear);
            // j=10
            int j=Integer.parseInt(startTimeMonth)+1;
            // chazhi=6
            int chazhi=((Integer.parseInt(endTimeYear)-Integer.parseInt(startTimeYear))*12+Integer.parseInt(endTimeMonth)-Integer.parseInt(startTimeMonth)-1);
            String startDate="";
            String endDate="";
            for(int i=0;i<chazhi;i++){
                if(j>12){
                    j=1;
                    year++;
                }
                startDate=year+"/"+j+"/"+1;
                endDate=year+"/"+j+"/"+31;
                months.add(year+"/"+j);
                Integer num=memberService.findMemberCountBySameYearAndMonth(startDate,endDate);
                list.add(num);
                j++;
            }
            System.out.println(months);
            System.out.println(year);


            months.add(endTimeYear+"/"+endTimeMonth);
            Integer c=memberService.findMemberCountBySameYearAndMonth(endTimeYear+"/"+endTimeMonth+"/"+1,endTime);
            list.add(c);

            map.put("months",months);
            map.put("memberAmount",list);

            System.out.println("================================="+map);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);


        }


        /*Map<String,Object> map=new HashMap<>();
        List<String> months=new ArrayList<>();

        Calendar calendar=Calendar.getInstance();  //获得日历对象
        //计算过去一年的时间
        calendar.add(Calendar.MONTH,-12);  //获得当前时间往前推12个月的时间
        for(int i=0;i<12;i++){
            calendar.add(Calendar.MONTH,1);  //获得当前时间往后推一个月的日期
            Date date = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy.MM").format(date));
        }

        map.put("months",months);

        List<Integer> memberAmount =memberService.findMemberAmountByMouths(months);
        map.put("memberAmount",memberAmount);

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);*/
        return null;
    }


    /**
     * 年龄占比
     * @return
     */
    @RequestMapping("/getageReport")
    public Result getageReport() {
        List<Map<String,Object>> list=memberService.findAgeCount();

        Map<String,Object> map =new HashMap<>();
        map.put("ageCount",list);

        List<String> ageGroup=new ArrayList<>();
        for (Map<String, Object> m : list) {
            String name = (String) m.get("name");
            ageGroup.add(name);
        }

        map.put("ageGroup",ageGroup);

        return new Result(true,"获取各年龄占比成功！",map);

    }
}
